<!--  -->
<template>
  <div class=''>
    <el-form ref="formInline" :inline="true" size="small" :model="formInline" class="demo-form-inline">
      <el-form-item label="关键字" prop="user">
        <el-input v-model="formInline.user" placeholder="公司名称、电话"></el-input>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="formInline.value_ser"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formInline.status" placeholder="请选择状态">
          <el-option label="封禁" value="0"></el-option>
          <el-option label="正常" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="getCompanyListFun"
          class="queryButton"
          icon="el-icon-search">查询</el-button>
        <el-button
          class="resetButton"
          @click="resetcompanySearch('formInline')"
          icon="el-icon-refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form>
      <el-button
        type="primary"
        plain
        class="queryButton"
        @click="addRoleBtn"
        v-permissions="'company:add'"
        icon="el-icon-plus">新增公司</el-button>
    </el-form>
    <!-- 新增公司弹框 -->
    <el-dialog
      title="新增公司"
      :visible.sync="isShowaddCompany"
      @close="resetQuery('companyForm')"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      width="30%">
      <el-form ref="companyForm" size="small" :model="companyFromAdd" :rules="addCompanyRule" label-width="80px">
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="companyFromAdd.address"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-cascader
            class="widthSmall"
            size="large"
            :options="options"
            v-model="companyFromAdd.city"
            @change="addressChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="公司名称" prop="comName">
          <el-input v-model="companyFromAdd.comName"></el-input>
        </el-form-item>
        <el-form-item label="人数" prop="count">
          <el-input type="number" v-model="companyFromAdd.count"></el-input>
        </el-form-item>
        <el-form-item label="到期时间" prop="expireTime">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="companyFromAdd.expireTime"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="ip白名单" prop="ipList">
          <el-input v-model="companyFromAdd.ipList" type="textarea" placeholder="请输入内容,回车换行输入下一个"></el-input>
        </el-form-item>
        <el-form-item label="ip状态" prop="ipStatus">
          <el-select v-model="companyFromAdd.ipStatus" placeholder="请选择">
            <el-option
            v-for="(item,index) in ipStatusArr"
            :key="index"
            :label="item.name"
            :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="companyFromAdd.phone"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="companyFromAdd.status" placeholder="请选择">
            <el-option
            v-for="(item,index) in ipStatusArr"
            :key="index"
            :label="item.name"
            :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="width: 100%; text-align: center;">
        <el-button 
          type="primary"
          plain
          @click="submitRole"
          class="queryButton">保存</el-button>
        <el-button
          plain
          class="resetButton"
          @click="resetQuery('companyForm')">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 公司详情弹框 -->
    <el-dialog
      title="公司详情"
      :visible.sync="companyDetailPop"
      @close="closeDetail"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="true"
      width="40%">
      <el-form
        ref="companyForm"
        size="small"
        :model="companyFromDetail"
        :rules="detailCompanyRule"
        :disabled="isDisable"
        label-width="80px">
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="companyFromDetail.address"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-cascader
            class="widthSmall"
            size="large"
            :options="options"
            v-model="companyFromDetail.city"
            @change="addressChangeForDetail">
          </el-cascader>
        </el-form-item>
        <el-form-item label="公司名称" prop="comName">
          <el-input v-model="companyFromDetail.comName"></el-input>
        </el-form-item>
        <el-form-item label="人数" prop="count">
          <el-input type="number" v-model="companyFromDetail.count"></el-input>
        </el-form-item>
        <el-form-item label="到期时间" prop="expireTime">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="companyFromDetail.expireTime"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="ip白名单" prop="ipList">
          <el-input v-model="companyFromDetail.ipList" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="ip状态" prop="ipStatus">
          <el-select v-model="companyFromDetail.ipStatus" placeholder="请选择">
            <el-option
            v-for="(item,index) in ipStatusArr"
            :key="index"
            :label="item.name"
            :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="companyFromDetail.phone"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="companyFromDetail.status" placeholder="请选择">
            <el-option
            v-for="(item,index) in ipStatusArr"
            :key="index"
            :label="item.name"
            :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form class="buttons">
        <el-button
          type="primary"
          class="submitButton"
          @click="setConfigUserRole"
          v-permissions="'company:update'"
          v-if="isDisable">修改</el-button>
        <el-button
          type="primary"
          class="submitButton"
          @click="addConfigUserRole"
          v-if="!isDisable">保存</el-button>
        <el-button
          class="resetButton"
          @click="closeDetail">关闭</el-button>
      </el-form>
    </el-dialog>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      :header-cell-style="{ background:'#f8f8f9',color:'#515a6e'}"
      size="mini"
      style="width: 100%; margin-top: 5px;">
      <el-table-column
        type="index"
        label="序号"
        width="50">
      </el-table-column>
      <el-table-column
        prop="name"
        label="公司名称"
        width="90">
      </el-table-column>
      <el-table-column
        prop="city"
        label="公司地址"
        width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.city+scope.row.address }}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="ipStatus"
        label="IP状态"
        width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.ipStatus === 0 ? '停用' : '正常'}}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.status === 0 ? '封禁' : '正常'}}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        width="100">
      </el-table-column>
      <el-table-column
        prop="expireTime"
        width="120"
        :show-overflow-tooltip="true"
        label="到期时间">
          <template slot-scope="scope">
            <span>{{ timestampToDate(scope.row.expireTime) }}</span>
          </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="getCompanyDetail(scope.row)"
          >详情</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deletCompany(scope.row.id,scope.row.companyName)"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      class="pagination_container"
      :total="paginationForOut.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="paginationForOut.page"
      :limit.sync="paginationForOut.pageSize"
      @pagination="getCompanyListFun"
    />
  </div>
</template>

<script>
import { companyAdd, companyList,companyUpdate,companyDelete } from '@/request/company';
import { provinceAndCityData, CodeToText } from 'element-china-area-data'
import { timestampToDate_setFun } from '@/until/paramRou'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
  //这里存放数据
    return {
      // 新增弹框
      options: provinceAndCityData, // 省市区数据
      cityCode: null,
      cityProvince: null,
      companyFromAdd: {
        address: '',
        city: '',
        cityCode: '',
        comName: '',
        count: null,
        expireTime: '',
        ipList: '',
        ipStatus: '',
        phone: '',
        status: ''
      },
      addCompanyRule: {
        address: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ],
        city: [
          { required: true, trigger: 'change', message: '请选择城市' }
        ],
        comName: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        count: [
          { required: true, trigger: 'blur', message: '请输入人数' }
        ],
        expireTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        ipStatus: [
          { required: true, trigger: 'change', message: '请选择ip状态' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        status: [
          { required: true, trigger: 'change', message: '请选择状态' }
        ],
      },
      isShowaddCompany: false,
      ipStatusArr: [
        {
          name: '停用',
          id: 0
        },
        {
          name: '正常',
          id: 1
        }
      ],
      statusArr:[
        {
          name: '封禁',
          id: 0
        },
        {
          name: '正常',
          id: 1
        }
      ],
      // end
      // 公司详情
      isDisable: true,
      companyDetailPop: false,
      cityProvinceDetail: null,
      cityCodeDetail: null, 
      companyFromDetail: {
        address: '',
        city: '',
        cityCode: '',
        comName: '',
        count: null,
        expireTime: '',
        ipList: '',
        ipStatus: '',
        phone: '',
        status: '',
        comId: ''
      },
      detailCompanyRule: {
        address: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ],
        city: [
          { required: true, trigger: 'change', message: '请选择城市' }
        ],
        comName: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        count: [
          { required: true, trigger: 'blur', message: '请输入人数' }
        ],
        expireTime: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        ipStatus: [
          { required: true, trigger: 'change', message: '请选择ip状态' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        status: [
          { required: true, trigger: 'change', message: '请选择状态' }
        ],
      },
      // end
      paginationForOut: {
        page: 1,
        pageSize: 10,
        total: 20
      },
      // 搜索框
      formInline: {
        user: '',
        status: null,
        value_ser: []
      },
      tableData: []
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    // 获取公司列表
    getCompanyListFun(){
      let companyListObj = {} 
      if (this.formInline.value_ser === null) {
        companyListObj = {
          kw: this.formInline.user,
          status: this.formInline.status,
          startTime: '',
          endTime: '',
          limit: this.paginationForOut.pageSize,
          page: this.paginationForOut.page,
        }
      } else {
        companyListObj = {
          kw: this.formInline.user,
          status: this.formInline.status,
          startTime: timestampToDate_setFun(this.formInline.value_ser[0]) === 'NaN-aN-aN' ? '' : timestampToDate_setFun(this.formInline.value_ser[0]),
          endTime: timestampToDate_setFun(this.formInline.value_ser[1]) === 'NaN-aN-aN' ? '' : timestampToDate_setFun(this.formInline.value_ser[1]),
          limit: this.paginationForOut.pageSize,
          page: this.paginationForOut.page,
        }
      }
      companyList(companyListObj).then(res => {
        // console.log(res);
        if(res.code === '200') {
          this.tableData = res.data.records
          if (res.data.total > 0 && Math.ceil(res.data.total / this.paginationForOut.size) < this.paginationForOut.page) {
            this.paginationForOut.page = Math.ceil(res.data.total / this.paginationForOut.size)
            this.getCompanyListFun()
          } else {
            this.paginationForOut.total = res.data.total
          }
        } else {
          this.tableData = []
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      }).catch(err => {
        this.$message({
          message: '服务器忙~',
          type: 'warning'
        })
      })
    },
    // 新增公司
    // 地址选择 - 新增
    addressChange (arr) {
      this.cityCode = arr[0]+"-"+arr[1]
      this.cityProvince = CodeToText[arr[0]] + CodeToText[arr[1]]
    },
    // 打开新增公司弹框
    addRoleBtn(){
      this.isShowaddCompany = true
    },
    // 关闭新增弹框
    closeDia(){
      this.isShowaddCompany = false
      this.dialogVisible = false
    },
    // 提交新公司
    submitRole(){
      this.$refs.companyForm.validate((valid) => {
        if (valid) {
          this.companyFromAdd.expireTime = timestampToDate_setFun(this.companyFromAdd.expireTime)
          this.companyFromAdd.cityCode = this.cityCode 
          this.companyFromAdd.city = this.cityProvince
          companyAdd(this.companyFromAdd).then(res => {
            if (res.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.isShowaddCompany = false
              this.getCompanyListFun()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          }).catch(err => {
            this.$message({
              message: '服务器忙~',
              type: 'warning'
            })
          })
        }
      })
    },
    // 删除公司
    // deletCompany(id,name){
    //   this.$confirm(`是否确认删除’${name}‘`, '提示', {
    //     type: 'warning',
    //     confirmButtonText: '确定',
    //     showCancelButton: '取消',
    //     distinguishCancelAndClose: false
    //   }).then(() => {
    //     companyDelete(id).then(res => {
    //       if (res.code === '200') {
    //         this.getCompanyListFun()
    //         this.$message({
    //           type: 'success',
    //           message: '删除成功!'
    //         })
    //       } else {
    //         this.$message({
    //           type: 'error',
    //           message: res.message
    //         })
    //       }
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '取消!'
    //     })
    //   })
    // },
    // 打开公司详情 / 修改
    getCompanyDetail (detail) {
      // console.log(detail,13212)
      const cityEnd = detail.cityCode.length
      const tagNum = detail.cityCode.indexOf('-')
      const provinceCode = detail.cityCode.substring(0, tagNum)
      const cityForCode = detail.cityCode.substring(tagNum + 1, cityEnd)
      this.companyFromDetail.address = detail.address
      this.cityCodeDetail = detail.cityCode
      this.cityProvinceDetail = detail.city
      this.companyFromDetail.comId = detail.id
      this.companyFromDetail.city = [provinceCode,cityForCode]
      this.companyFromDetail.comName = detail.name
      this.companyFromDetail.count = detail.count
      this.companyFromDetail.expireTime = detail.expireTime
      this.companyFromDetail.ipList = detail.ipWhiteList
      this.companyFromDetail.ipStatus = detail.ipStatus
      this.companyFromDetail.phone = detail.phone
      this.companyFromDetail.status = detail.status
      this.companyDetailPop = true
      // console.log(this.companyFromDetail);
      
    },
    // 关闭公司详情
    closeDetail(){
      this.companyDetailPop = false
    },
    // 地址选择 - 修改
    addressChangeForDetail(arr){
      this.cityCodeDetail = arr[0]+"-"+arr[1]
      this.cityProvinceDetail = CodeToText[arr[0]] + CodeToText[arr[1]]
    },
    // 确认保存
    setConfigUserRole () {
      this.$confirm('是否确认修改公司信息', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        distinguishCancelAndClose: false
      }).then(() => {
        this.isDisable = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    // 保存修改详情按钮
    addConfigUserRole () {
      const company = {
        address: this.companyFromDetail.address,
        city: this.cityProvinceDetail,
        cityCode: this.cityCodeDetail,
        comId: this.companyFromDetail.comId,
        comName: this.companyFromDetail.comName,
        count: this.companyFromDetail.count,
        expireTime: timestampToDate_setFun(this.companyFromDetail.expireTime),
        ipList: this.companyFromDetail.ipList,
        ipStatus: this.companyFromDetail.ipStatus,
        phone: this.companyFromDetail.phone,
        status: this.companyFromDetail.status
      }
      companyUpdate(company).then(res => {
        if (res.code === '200') {
          this.companyDetailPop = false
          this.getCompanyListFun()
          this.isDisable = true
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      }).catch(err => {
        this.$message({
          message: '服务器忙~',
          type: 'warning'
        })
      })
    },
    // end
    // 重置 - 搜索 - 新增
    resetQuery(fromName) {
      // this.resetForm(fromName)
      this.$refs[fromName].resetFields();
      this.isShowaddCompany = false
    },
    resetcompanySearch(fromName){
      this.formInline.value_ser = null
      // this.resetForm(fromName)
      this.$refs[fromName].resetFields();
      this.getCompanyListFun()
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getCompanyListFun()
  }
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
  
.buttons {
  width: 100%;
  text-align: center;
}
</style>
